class CrawlerApp {
  constructor() {
    this.timerId = null
    this.initDOM()
    this.loadConfig()
    this.bindEvents()
  }

  initDOM() {
    this.elements = {
      ignorekeywords: document.getElementById('ignorekeywords'),
      searchtype: document.getElementById('searchtype'),
      bidType: document.getElementById('bidType'),
      bidSort: document.getElementById('bidSort'),
      pinMu: document.getElementById('pinMu'),
      keywords: document.getElementById('keywords'), // 新增关键词输入框
      scheduleEnabled: document.getElementById('scheduleEnabled'),
      interval: document.getElementById('interval'),
      saveToExcel: document.getElementById('saveToExcel'),
      savePath: document.getElementById('savePath'), // 新增保存路径输入框
      startBtn: document.getElementById('startBtn'),
      output: document.getElementById('output'),
      loading: document.getElementById('loading'), // 新增loading元素
      homeTab: document.getElementById('homeTab'),
      scheduleTab: document.getElementById('scheduleTab'),
      homePage: document.getElementById('homePage'),
      schedulePage: document.getElementById('schedulePage'),
      savedConfigs: document.getElementById('savedConfigs'),
      searchTime: document.getElementById('searchTime'), // 新增时间选择框
      datePickerRow: document.getElementById('datePickerRow'),
      startDate: document.getElementById('startDate'),
      endDate: document.getElementById('endDate'),
      scheduleBtn: document.getElementById('scheduleBtn'),
      scheduleModal: document.getElementById('scheduleModal'),
      closeModal: document.querySelector('.close'),
      saveScheduleBtn: document.getElementById('saveScheduleBtn'),
      scheduleName: document.getElementById('scheduleName'),
      scheduleInterval: document.getElementById('scheduleInterval')
    }
  }

  async loadConfig() {
    try {
      const config = await window.electronAPI.loadConfig()
      this.updateForm(config)
      this.loadSavedConfigs()
    } catch (err) {
      this.showError('配置加载失败', err)
    }
  }

  updateForm(config) {
    const { searchParams, schedule } = config
    if (this.elements.searchtype) this.elements.searchtype.value = searchParams.searchtype
    if (this.elements.ignorekeywords) this.elements.ignorekeywords.value = (searchParams.ignorekeywords || []).join(', ') // Ensure it's a comma-separated string
    if (this.elements.bidType) this.elements.bidType.value = searchParams.bidType
    if (this.elements.bidSort) this.elements.bidSort.value = searchParams.bidSort
    if (this.elements.pinMu) this.elements.pinMu.value = searchParams.pinMu
    if (this.elements.scheduleEnabled) this.elements.scheduleEnabled.checked = schedule.enabled
    if (this.elements.interval) this.elements.interval.value = schedule.interval
    if (this.elements.savePath) this.elements.savePath.value = config.savePath || 'C:\\' // 设置默认保存路径
    if (this.elements.searchTime) this.elements.searchTime.value = searchParams.timeType // 设置时间选择框的值
    if (searchParams.timeType === 6) {
      if (this.elements.datePickerRow) this.elements.datePickerRow.style.display = 'flex'
      if (this.elements.startDate) this.elements.startDate.value = searchParams.start_time.replace(/:/g, '-')
      if (this.elements.endDate) this.elements.endDate.value = searchParams.end_time.replace(/:/g, '-')
    } else {
      if (this.elements.datePickerRow) this.elements.datePickerRow.style.display = 'none'
    }
  }

  bindEvents() {
    if (this.elements.startBtn) {
      this.elements.startBtn.addEventListener('click', () => {
        console.log('Start button clicked');
        this.startCrawl();
      });
    }

    // 输入验证
    if (this.elements.interval) {
      this.elements.interval.addEventListener('input', (e) => {
        e.target.value = Math.max(300, parseInt(e.target.value) || 300)
      })
    }

    if (this.elements.searchTime) {
      this.elements.searchTime.addEventListener('change', (e) => {
        if (parseInt(e.target.value) === 6) {
          if (this.elements.datePickerRow) this.elements.datePickerRow.style.display = 'flex'
        } else {
          if (this.elements.datePickerRow) this.elements.datePickerRow.style.display = 'none'
        }
      })
    }

    if (this.elements.savePath) {
      this.elements.savePath.addEventListener('click', async () => {
        const result = await window.electronAPI.selectDirectory()
        if (result.filePaths && result.filePaths.length > 0) {
          this.elements.savePath.value = result.filePaths[0]
        }
      })
    }

    if (this.elements.scheduleBtn) {
      this.elements.scheduleBtn.addEventListener('click', () => {
        if (this.elements.scheduleModal) this.elements.scheduleModal.style.display = 'block'
      })
    }

    if (this.elements.closeModal) {
      this.elements.closeModal.addEventListener('click', () => {
        if (this.elements.scheduleModal) this.elements.scheduleModal.style.display = 'none'
      })
    }

    if (this.elements.saveScheduleBtn) {
      this.elements.saveScheduleBtn.addEventListener('click', () => {
        this.saveScheduleConfig()
      })
    }

    if (this.elements.homeTab) {
      this.elements.homeTab.addEventListener('click', () => {
        this.showPage('home');
      });
    }

    if (this.elements.scheduleTab) {
      this.elements.scheduleTab.addEventListener('click', () => {
        this.showPage('schedule');
      });
    }
  }

  async startCrawl() {
    console.log('startCrawl method called');
    const config = this.getCurrentConfig();
    console.log('Current config:', config);
    
    try {
      this.showLoading();
      this.clearOutput();
      const result = await window.electronAPI.startCrawl(config);
      console.log('Crawl result:', result);
      this.appendOutput(result);
      
      if (config.schedule.enabled) {
        this.setupSchedule(config);
      }

      if (this.elements.saveToExcel.checked && result) {
        const resultsArray = Array.isArray(result.results) ? result.results : [result.results];
        await window.electronAPI.saveToExcel(resultsArray, this.elements.savePath.value);
        console.log('Results saved to Excel');
      }
    } catch (err) {
      console.error('Crawl error:', err);
      this.showError('执行失败', err);
    } finally {
      this.hideLoading();
    }
  }

  getCurrentConfig() {
    const searchTime = parseInt(this.elements.searchTime.value);
    const today = new Date();
    const formatDate = (date) => date.toISOString().split('T')[0].replace(/-/g, ':');

    let start_time, end_time;
    switch (searchTime) {
      case 0: // 今天
        start_time = end_time = formatDate(today);
        break;
      case 1: // 近3日
        start_time = formatDate(new Date(today.setDate(today.getDate() - 3)));
        end_time = formatDate(new Date());
        break;
      case 2: // 近1周
        start_time = formatDate(new Date(today.setDate(today.getDate() - 7)));
        end_time = formatDate(new Date());
        break;
      case 3: // 近1月
        start_time = formatDate(new Date(today.setMonth(today.getMonth() - 1)));
        end_time = formatDate(new Date());
        break;
      case 4: // 近3月
        start_time = formatDate(new Date(today.setMonth(today.getMonth() - 3)));
        end_time = formatDate(new Date());
        break;
      case 5: // 近半年
        start_time = formatDate(new Date(today.setMonth(today.getMonth() - 6)));
        end_time = formatDate(new Date());
        break;
      case 6: // 指定时间
        start_time = this.elements.startDate ? this.elements.startDate.value.replace(/-/g, ':') : '';
        end_time = this.elements.endDate ? this.elements.endDate.value.replace(/-/g, ':') : '';
        break;
      default:
        start_time = end_time = formatDate(today);
    }

    return {
      keywords: this.elements.keywords ? this.elements.keywords.value.split(',').map(kw => kw.trim()) : [], // 获取并处理关键词
      ignorekeywords: this.elements.ignorekeywords && this.elements.ignorekeywords.value.trim() !== "" ? this.elements.ignorekeywords.value.split(',').map(kw => kw.trim()) : ["示例忽略词"], // 获取并处理忽略关键词
      searchParams: {
        searchtype: this.elements.searchtype ? parseInt(this.elements.searchtype.value) : 1,
        page_index: 1,
        bidSort: this.elements.bidSort ? parseInt(this.elements.bidSort.value) : 0,
        bidType: this.elements.bidType ? parseInt(this.elements.bidType.value) : 0,
        pinMu: this.elements.pinMu ? parseInt(this.elements.pinMu.value) : 0,
        timeType: searchTime,
        start_time: start_time,
        end_time: end_time
      },
      schedule: {
        enabled: this.elements.scheduleEnabled ? this.elements.scheduleEnabled.checked : false,
        interval: this.elements.interval ? parseInt(this.elements.interval.value) : 3600
      },
      savePath: this.elements.savePath ? this.elements.savePath.value : 'C:\\' // 获取保存路径
    }
  }

  async saveConfig(config) {
    try {
      await window.electronAPI.saveConfig(config);
      console.log('Config saved:', config);
      this.loadSavedConfigs();
    } catch (err) {
      console.error('Save config error:', err);
      this.showError('保存配置失败', err);
    }
  }

  async saveScheduleConfig() {
    const scheduleConfig = {
      name: this.elements.scheduleName ? this.elements.scheduleName.value : '',
      enabled: this.elements.scheduleEnabled ? this.elements.scheduleEnabled.checked : false,
      interval: this.elements.scheduleInterval ? parseInt(this.elements.scheduleInterval.value) : 3600
    }
    console.log('Saving schedule config:', scheduleConfig);
    // Save the schedule config to the store
    const config = this.getCurrentConfig();
    config.schedule = scheduleConfig;
    await this.saveConfig(config);
    if (this.elements.scheduleModal) this.elements.scheduleModal.style.display = 'none';
  }

  async loadSavedConfigs() {
    try {
      const configs = await window.electronAPI.loadSavedConfigs();
      this.elements.savedConfigs.innerHTML = configs.map((config, index) => `
        <div class="config-entry">
          <h4 class="config-name" data-index="${index}">${config.schedule.name || `配置 ${index + 1}`}</h4>
          <div class="config-details">
            <div class="config-details-row">
              <p><strong>搜索类型:</strong> ${config.searchParams.searchtype === 1 ? '搜标题' : '搜全文'}</p>
              <p><strong>类型:</strong> ${this.getBidTypeName(config.searchParams.bidType)}</p>
              <p><strong>类别:</strong> ${this.getBidSortName(config.searchParams.bidSort)}</p>
              <p><strong>品目:</strong> ${this.getPinMuName(config.searchParams.pinMu)}</p>
              <p><strong>时间:</strong> ${config.searchParams.start_time}-${config.searchParams.end_time}</p>
            </div>
            <div class="config-details-row">
              <p><strong>关键词:</strong> ${config.keywords.join(', ')}</p>
            </div>
            <div class="config-details-row">
              <p><strong>忽略词:</strong> ${config.ignorekeywords.join(', ')}</p>
            </div>
            <div class="config-details-row">
              <p><strong>保存路径:</strong> ${config.savePath}</p>
            </div>
          </div>
          <pre class="config-json">${JSON.stringify(config, null, 2)}</pre>
        </div>
      `).join('');

      // Add event listeners for toggling JSON view
      document.querySelectorAll('.config-name').forEach(element => {
        element.addEventListener('click', (e) => {
          const index = e.target.getAttribute('data-index');
          const jsonElement = document.querySelector(`.config-entry:nth-child(${parseInt(index) + 1}) .config-json`);
          if (jsonElement) {
            jsonElement.style.display = jsonElement.style.display === 'none' ? 'block' : 'none';
          }
        });
      });
    } catch (err) {
      console.error('Load saved configs error:', err);
      this.showError('加载已保存配置失败', err);
    }
  }

  getBidTypeName(bidType) {
    const bidTypes = {
      0: '所有类型',
      1: '公开招标',
      2: '询价公告',
      3: '竞争性谈判',
      4: '单一来源',
      5: '资格预审',
      6: '邀请公告',
      7: '中标公告',
      8: '更正公告',
      9: '其他公告',
      10: '竞争性磋商',
      11: '成交公告',
      12: '终止公告'
    };
    return bidTypes[bidType] || '未知类型';
  }

  getBidSortName(bidSort) {
    const bidSorts = {
      0: '所有类别',
      1: '中央公告',
      2: '地方公告'
    };
    return bidSorts[bidSort] || '未知类别';
  }

  getPinMuName(pinMu) {
    const pinMus = {
      0: '所有品目',
      1: '货物类',
      2: '工程类',
      3: '服务类'
    };
    return pinMus[pinMu] || '未知品目';
  }

  getTimeTypeName(timeType) {
    const timeTypes = {
      0: '今天',
      1: '近3日',
      2: '近1周',
      3: '近1月',
      4: '近3月',
      5: '近半年',
      6: '指定时间'
    };
    return timeTypes[timeType] || '未知时间';
  }

  setupSchedule(config) {
    if (this.timerId) clearInterval(this.timerId)
    
    this.timerId = setInterval(async () => {
      try {
        const result = await window.electronAPI.startCrawl(config)
        this.appendOutput(`定时执行结果：${result}`)
        if (this.elements.saveToExcel.checked && result) {
          await window.electronAPI.saveToExcel(result.results, this.elements.savePath.value);
          console.log('Results saved to Excel');
        }
      } catch (err) {
        this.showError('定时执行失败', err)
      }
    }, config.schedule.interval * 1000)
  }

  appendOutput(result) {
    const { elapsed_time, result_count, query_params, results } = result;
    this.elements.output.innerHTML += `
      <div class="log-entry">
        <strong>耗时:</strong> ${elapsed_time ? elapsed_time.toFixed(2) : 'N/A'} 秒<br>
        <strong>结果数目:</strong> ${result_count || 0}<br>
        <strong>查询参数:</strong> <pre>${JSON.stringify(query_params, null, 2)}</pre><br>
        <strong>结果:</strong> <pre>${JSON.stringify(results, null, 2)}</pre>
      </div>
    `;
    this.elements.output.scrollTop = this.elements.output.scrollHeight;
  }

  clearOutput() {
    this.elements.output.innerHTML = ''
  }

  formatOutput(text) {
    if (typeof text !== 'string') {
      text = JSON.stringify(text, null, 2);
    }
    return text.replace(/\n/g, '<br>').replace(/ /g, '&nbsp;')
  }

  showError(title, err) {
    console.error(`${title}:`, err)
    this.appendOutput(`<span class="error">${title}: ${err.message}</span>`)
  }

  showLoading() {
    if (this.elements.loading) this.elements.loading.style.display = 'block';
  }

  hideLoading() {
    if (this.elements.loading) this.elements.loading.style.display = 'none';
  }

  showPage(page) {
    if (page === 'home') {
      if (this.elements.homePage) this.elements.homePage.classList.add('active');
      if (this.elements.schedulePage) this.elements.schedulePage.classList.remove('active');
      if (this.elements.homeTab) this.elements.homeTab.classList.add('active');
      if (this.elements.scheduleTab) this.elements.scheduleTab.classList.remove('active');
    } else if (page === 'schedule') {
      if (this.elements.homePage) this.elements.homePage.classList.remove('active');
      if (this.elements.schedulePage) this.elements.schedulePage.classList.add('active');
      if (this.elements.homeTab) this.elements.homeTab.classList.remove('active');
      if (this.elements.scheduleTab) this.elements.scheduleTab.classList.add('active');
    }
  }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
  new CrawlerApp()
})